<?php

namespace Acme\EventBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Acme\EventBundle\Entity\Information;
use Acme\EventBundle\Entity\Inscription;
use Acme\EventBundle\Entity\Feedback;
use Acme\EventBundle\Entity\Aperolocation;
use Doctrine\ORM\EntityRepository;

// these import the "@Route" and "@Template" annotations
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Validator\Constraints\DateTime;

/**
 * @Route("/auth/security/event")
 */
class EventController extends Controller {
	
	/**
	 * @Route("/setEventUser/{id}", name="setevent_user")
	 * @Template()
	 */
	public function setEventUserAction($id) {
		$pagedata = $this->get ( 'common_pagedata' );
		$arr_data = $pagedata->getCommonSecurity ();
		
		$em = $this->getDoctrine ()->getManager ();
		
		$inscription = $em->getRepository ( 'AcmeEventBundle:Inscription' )->findByInformationAndUser ( $id, $arr_data ["usr"]->getId () );
		
		if ($inscription->getParticipate () != - 1) {
			$_participate = $inscription->getParticipate ();
		} else {
			$_participate = 1;
		}
		
		$form = $this->createFormBuilder ( $this->getRequest ()->get ( 'form' ) )->add ( 'participate', 'choice', array (
				'expanded' => true,
				'choices' => array (
						'1' => 'Ich bin dabei',
						'0' => 'Ich bin nicht dabei' 
				)
				,
				'data' => $_participate,
				'label' => 'Anmeldung' 
		) )->add ( 'answer', 'textarea', array (
				'label' => 'Kommentar',
				'required' => false 
		) )->add ( 'save', 'submit', array (
				'label' => 'Erfassen' 
		) )->getForm ();
		
		$form->handleRequest ( $this->getRequest () );
		
		if ($form->isValid ()) {
			
			$information = $em->getRepository ( 'AcmeEventBundle:Information' )->findByPerson ( $id );
			$timestamp = new \DateTime ( 'now' );
			$inscription->setParticipate ( $this->getRequest ()->get ( 'form' )['participate'] );
			$inscription->setDatum ( $timestamp );
			$em->persist ( $inscription );
			$em->flush ();
			if ($this->getRequest ()->get ( 'form' )['participate']) {
				$this->get ( 'session' )->getFlashBag ()->set ( 'information', 'Freuen uns Dich zu sehen!' );
			} else {
				$this->get ( 'session' )->getFlashBag ()->set ( 'information', 'Schade bist Du nicht dabei!' );
			}
			
			if (strlen ( $this->getRequest ()->get ( 'form' )['answer'] ) > 0) {
				$feedback = new Feedback ();
				$feedback->setDatum ( $timestamp );
				$feedback->setAnswer ( $this->getRequest ()->get ( 'form' )['answer'] );
				$feedback->setInscription ( $inscription );
				$em->persist ( $feedback );
				$em->flush ();
			}
			
			// mail
			$mail = $this->get ( 'common_mail' );
			$users = $em->getRepository ( 'AcmeUserBundle:User' )->findAllPerson ();
			foreach ( $users as $user ) {
				$email_to = $user ['email'];
				$message = $this->renderView ( 'AcmeEventBundle:Event:emailUserParticipateEvent.html.twig', array (
						'firstname' => $user ['firstname'],
						'eventmonat' => $information ['datum']->format ( 'F' ),
						'eventdatum' => $information ['datum']->format ( 'd.m.Y' ),
						'eventorganisator' => $information ['firstname'],
						'id' => $information ['id'],
						'answer' => $this->getRequest ()->get ( 'form' )['answer'],
						'participate' => $this->getRequest ()->get ( 'form' )['participate'],
						'personfirstname' => $arr_data ["persons"]->getFirstname () 
				) );
				
				if ($this->getRequest ()->get ( 'form' )['participate']) {
					$_text = ' ist für den Event vom ' . $information ['datum']->format ( 'd.m.Y' ) . ' dabei';
				} else {
					$_text = ' ist für den Event vom ' . $information ['datum']->format ( 'd.m.Y' ) . ' leider nicht dabei';
				}
				
				$subject = 'SELV - book: ' . $arr_data ["persons"]->getFirstname () . $_text;
				$mail->sendMail ( $subject, $message, $email_to );
			}
			
			return $this->redirect ( $this->generateUrl ( 'new_feedback', array (
					'id' => $id 
			) ) );
		}
		
		return array (
				'user' => $arr_data ["usr"],
				'personimagest' => $arr_data ["personimagest"],
				'personimages' => $arr_data ["personimages"],
				'persons' => $arr_data ["persons"],
				'usersinformation' => $arr_data ["usersinformation"],
				'information' => $em->getRepository ( 'AcmeEventBundle:Information' )->find ( $id ),
				'inscriptions' => $arr_data ["inscriptions"],
				'inscription' => $inscription,
				'information_datum' => $arr_data ["information_datum"],
				'form' => $form->createView () 
		);
	}
	
	/**
	 * @Route("/showEvents", name="show_events")
	 * @Template()
	 */
	public function showEventsAction() {
		$em = $this->getDoctrine ()->getManager ();
		$informations = $em->getRepository ( 'AcmeEventBundle:Information' )->findAllPersons ();
		
		$pagedata = $this->get ( 'common_pagedata' );
		$arr_data = $pagedata->getCommonSecurity ();
		
		return array (
				'user' => $arr_data ["usr"],
				'personimagest' => $arr_data ["personimagest"],
				'personimages' => $arr_data ["personimages"],
				'persons' => $arr_data ["persons"],
				'usersinformation' => $arr_data ["usersinformation"],
				'inscriptions' => $arr_data ["inscriptions"],
				'information_datum' => $arr_data ["information_datum"],
				'informations' => $informations 
		)
		;
	}
	
	/**
	 * @Route("/setEventOrganisator/{id}", name="setevent_organisator")
	 * @Template()
	 */
	public function setEventOrganisatorAction($id) {
		$em = $this->getDoctrine ()->getManager ();
		$usr = $this->container->get ( 'security.context' )->getToken ()->getUser ();
		
		$form = $this->createFormBuilder ( $this->getRequest ()->get ( 'form' ) )->

		add ( 'aperolocation', 'entity', array (
				'class' => 'AcmeEventBundle:Aperolocation',
				'query_builder' => function (EntityRepository $er) {
					return $er->createQueryBuilder ( 'a' )->orderBy ( 'a.name', 'ASC' );
				} 
		) )->add ( 'location', 'text', array (
				'required' => false 
		) )->add ( 'street', 'text', array (
				'required' => false 
		) )->add ( 'postcode', 'text', array (
				'required' => false 
		) )->add ( 'city', 'text', array (
				'required' => false 
		) )->add ( 'email', 'text' )->add ( 'telefon', 'text' )->add ( 'description', 'textarea' )->add ( 'save', 'submit', array (
				'label' => 'Erfassen und SELV Member informieren' 
		) )->getForm ();
		
		$form->handleRequest ( $this->getRequest () );
		
		if ($form->isValid ()) {
			$this->get ( 'session' )->getFlashBag ()->set ( 'information', 'Danke für die Organisation !' );
			$information = $em->getRepository ( 'AcmeEventBundle:Information' )->find ( $id );
			$information->setLocation ( $this->getRequest ()->get ( 'form' )['location'] );
			$information->setStreet ( $this->getRequest ()->get ( 'form' )['street'] );
			$information->setPostcode ( $this->getRequest ()->get ( 'form' )['postcode'] );
			$information->setCity ( $this->getRequest ()->get ( 'form' )['city'] );
			$information->setDescription ( $this->getRequest ()->get ( 'form' )['description'] );
			$information->setAperolocation ( $em->getRepository ( 'AcmeEventBundle:Aperolocation' )->find ( $this->getRequest ()->get ( 'form' )['aperolocation'] ) );
			$em->persist ( $information );
			$em->flush ();
		}
		
		$arr_information = $em->getRepository ( 'AcmeEventBundle:Information' )->findByPersonAndInformation ( $id, $usr->getId () );
		
		if (! $arr_information) {
			$this->get ( 'session' )->getFlashBag ()->set ( 'error', 'Du bist nicht berechtigt diesen Event zu organisieren!' );
		}
		
		if ('POST' != $this->getRequest ()->getMethod ()) {
			$form->setData ( $arr_information );
		} else {
			// mail
			$information = $em->getRepository ( 'AcmeEventBundle:Information' )->findByPerson ( $id );
			$users = $em->getRepository ( 'AcmeUserBundle:User' )->findAllPerson ();
			$mail = $this->get ( 'common_mail' );
			foreach ( $users as $user ) {
				$email_to = $user ['email'];
				$message = $this->renderView ( 'AcmeEventBundle:Event:emailInfoEvent.html.twig', array (
						'firstname' => $user ['firstname'],
						'eventmonat' => $information ['datum']->format ( 'F' ),
						'eventdatum' => $information ['datum']->format ( 'd.m.Y' ),
						'eventorganisator' => $information ['firstname'],
						'id' => $information ['id'],
						'location' => $this->getRequest ()->get ( 'form' )['location'],
						'street' => $this->getRequest ()->get ( 'form' )['street'],
						'postcode' => $this->getRequest ()->get ( 'form' )['postcode'],
						'city' => $this->getRequest ()->get ( 'form' )['city'],
						'aperolocation' => $em->getRepository ( 'AcmeEventBundle:Aperolocation' )->find ( $this->getRequest ()->get ( 'form' )['aperolocation'] ),
						'description' => $this->getRequest ()->get ( 'form' )['description'] 
				) );
				$subject = 'Infos SELV Event vom ' . $information ['datum']->format ( 'd.m.Y' );
				$mail->sendMail ( $subject, $message, $email_to );
			}
			return $this->redirect ( $this->generateUrl ( 'new_feedback', array (
					'id' => $id 
			) ) );
		}
		
		$pagedata = $this->get ( 'common_pagedata' );
		$arr_data = $pagedata->getCommonSecurity ();
		
		return array (
				'user' => $arr_data ["usr"],
				'personimagest' => $arr_data ["personimagest"],
				'personimages' => $arr_data ["personimages"],
				'persons' => $arr_data ["persons"],
				'usersinformation' => $arr_data ["usersinformation"],
				'information' => $arr_information,
				'inscriptions' => $arr_data ["inscriptions"],
				'information_datum' => $arr_data ["information_datum"],
				'form' => $form->createView () 
		);
	}
	
	/**
	 * @Route("/newFeedback/{id}", name="new_feedback")
	 * @Template()
	 */
	public function newFeedbackAction($id) {
		$em = $this->getDoctrine ()->getManager ();
		
		$pagedata = $this->get ( 'common_pagedata' );
		$arr_data = $pagedata->getCommonSecurity ();
		
		$inscription = $em->getRepository ( 'AcmeEventBundle:Inscription' )->findByInformationAndUser ( $id, $arr_data ["usr"]->getId () );
		
		$information = $em->getRepository ( 'AcmeEventBundle:Information' )->findByInformation ( $id );
		
		if ($inscription->getParticipate () == - 1) {
			return $this->redirect ( $this->generateUrl ( 'setevent_user', array (
					'id' => $id 
			) ) );
		}
		
		$form = $this->createFormBuilder ( $this->getRequest ()->get ( 'form' ) )->add ( 'answer', 'textarea', array (
				'label' => 'Kommentar',
				'required' => false,
				'data' => '' 
		) )->add ( 'save', 'submit', array (
				'label' => 'Erfassen' 
		) )->getForm ();
		
		$form->handleRequest ( $this->getRequest () );
		
		if ($form->isValid ()) {
			$timestamp = new \DateTime ( 'now' );
			$this->get ( 'session' )->getFlashBag ()->set ( 'information', 'Danke für Deinen Eintrag !' );
			$feedback = new Feedback ();
			$feedback->setDatum ( $timestamp );
			$feedback->setAnswer ( $this->getRequest ()->get ( 'form' )['answer'] );
			$feedback->setInscription ( $inscription );
			$em->persist ( $feedback );
			$em->flush ();
			
			// mail
			$mail = $this->get ( 'common_mail' );
			$informationMail = $em->getRepository ( 'AcmeEventBundle:Information' )->findByPerson ( $id );
			$users = $em->getRepository ( 'AcmeUserBundle:User' )->findAllPerson ();
			foreach ( $users as $user ) {
				$email_to = $user ['email'];
				$message = $this->renderView ( 'AcmeEventBundle:Event:emailUserFeedbackEvent.html.twig', array (
						'firstname' => $user ['firstname'],
						'eventmonat' => $informationMail ['datum']->format ( 'F' ),
						'eventdatum' => $informationMail ['datum']->format ( 'd.m.Y' ),
						'eventorganisator' => $informationMail ['firstname'],
						'id' => $informationMail ['id'],
						'answer' => $this->getRequest ()->get ( 'form' )['answer'],
						'personfirstname' => $arr_data ["persons"]->getFirstname () 
				) );
				$_text = ' Nachricht von ' . $arr_data ["persons"]->getFirstname () . ' zum Event vom ' . $informationMail ['datum']->format ( 'd.m.Y' );
				
				$subject = 'SELV - book: ' . $_text;
				$mail->sendMail ( $subject, $message, $email_to );
			}
		}
		
		$feedbacks = $em->getRepository ( 'AcmeEventBundle:Feedback' )->findByEvent ( $id );
		
		return array (
				'user' => $arr_data ["usr"],
				'personimagest' => $arr_data ["personimagest"],
				'personimages' => $arr_data ["personimages"],
				'persons' => $arr_data ["persons"],
				'usersinformation' => $arr_data ["usersinformation"],
				'inscriptions' => $arr_data ["inscriptions"],
				'information_datum' => $arr_data ["information_datum"],
				'information' => $information,
				'feedbacks' => $feedbacks,
				'form' => $form->createView () 
		);
	}
	
	/**
	 * @Route("/overview", name="overview_events")
	 * @Template()
	 */
	public function overviewAction(Request $request) {
		$em = $this->getDoctrine ()->getManager ();
		
		$pagedata = $this->get ( 'common_pagedata' );
		$arr_data = $pagedata->getCommonSecurity ();
		
		$informations = $em->getRepository ( 'AcmeEventBundle:Information' )->findAllPersons ();
		
		return array (
				'user' => $arr_data ["usr"],
				'personimagest' => $arr_data ["personimagest"],
				'personimages' => $arr_data ["personimages"],
				'persons' => $arr_data ["persons"],
				'usersinformation' => $arr_data ["usersinformation"],
				'informations' => $informations,
				'inscriptions' => $arr_data ["inscriptions"],
				'information_datum' => $arr_data ["information_datum"],
				'current_year' => new \DateTime ( 'now' ) 
		);
	}
	
	/**
	 * @Route("/anmeldungen/{id}", name="anmeldungen")
	 * @Template()
	 */
	public function anmeldungenAction($id) {
		$em = $this->getDoctrine ()->getManager ();
		
		$pagedata = $this->get ( 'common_pagedata' );
		$arr_data = $pagedata->getCommonSecurity ();
		
		$inscriptionsByInformation = $em->getRepository ( 'AcmeEventBundle:Inscription' )->findAllByInscription ( $id );
		
		return array (
				'user' => $arr_data ["usr"],
				'personimagest' => $arr_data ["personimagest"],
				'personimages' => $arr_data ["personimages"],
				'persons' => $arr_data ["persons"],
				'usersinformation' => $arr_data ["usersinformation"],
				'inscriptions' => $arr_data ["inscriptions"],
				'inscriptions_by_information' => $inscriptionsByInformation,
				'information_datum' => $arr_data ["information_datum"],
				'current_year' => new \DateTime ( 'now' ),
				'selected_datum' => $em->getRepository ( 'AcmeEventBundle:Information' )->find ( $id ) 
		);
	}
	
	/**
	 * @Route("/statistikUser/{id}", name="statistik_user")
	 * @Template()
	 */
	public function statistikUserAction($id) {
		$em = $this->getDoctrine ()->getManager ();
		
		$pagedata = $this->get ( 'common_pagedata' );
		$arr_data = $pagedata->getCommonSecurity ();
		
		$inscriptionsByInformation = $em->getRepository ( 'AcmeEventBundle:Inscription' )->findAllByInscription ( $id );
		
		return array (
				'user' => $arr_data ["usr"],
				'personimagest' => $arr_data ["personimagest"],
				'personimages' => $arr_data ["personimages"],
				'persons' => $arr_data ["persons"],
				'usersinformation' => $arr_data ["usersinformation"],
				'inscriptions' => $arr_data ["inscriptions"],
				'information_datum' => $arr_data ["information_datum"],
				'current_year' => new \DateTime ( 'now' ) 
		);
	}
}
